import sys

from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSignal, QUuid, pyqtSlot
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout

from HttpApi.DataManager import DataManager
from HttpApi.JsonHttpClient import JsonHttpClient
from login_page import Ui_Form
# 1. 创建一个自定义的窗口类，继承自 QWidget
class LoginPage(QWidget, Ui_Form):
    # 创建信号槽需要在类定义体中创建, 这样PyQt才能识别, 否则会报错
    login_success = pyqtSignal(str)
    login_failed = pyqtSignal(str)
    httpClient = JsonHttpClient()

    def __init__(self):
        super().__init__()
        self.setupUi(self)  # 调用 UI 类的 setupUi 方法，设置窗口的 UI


        self.manager = DataManager()

        self.loginButton.clicked.connect(self.handle_login)
        self.goRegisterButton.clicked.connect(self.go_to_register_page)


    def go_to_register_page(self):
        print("切换到注册页面")


    def handle_login(self):
        # 读取account/password
        account = self.account.text()
        password = self.password.text()
        if not account or not password:
            self.login_failed.emit("用户名和密码不能为空")
            return
        # 发送登录请求
        self.loginButton.setEnabled(False)
        post = self.httpClient.post("/user/login", {"account": account, "passwordHash": password})
        self.loginButton.setEnabled(True)
        if post['code'] != 200:
            self.login_failed.emit(post['msg'])
            return
        if post['code'] == 200:
            print(f"登录成功！返回的data: {post}")
            self.manager.cache_data('token', 'Bearer '+post['data'])
            self.get_userinfo()
        print("登录按钮被点击了")

    def get_userinfo(self):
        print("获取用户信息")
        # 发送请求获取用户信息get: /user/auth-test, 并携带请求头
        get = self.httpClient.get("/user/auth-test", headers={"Authorization": self.manager.get_cached_data('token')})
        print(f"获取用户信息返回: {get}")
        if get['code'] == 200:
            self.manager.cache_data('userinfo', get['data']['userAccount'])
            self.login_success.emit(get['data']['userAccount']['name'])





# --- 程序的入口部分 ---
if __name__ == '__main__':
    # 设置应用程序高DPI缩放支持
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    # 2. 创建应用程序实例
    app = QApplication(sys.argv)
    # 3. 创建我们自定义的窗口实例
    my_app_window = LoginPage()

    # 4. 显示窗口
    my_app_window.show()

    # 5. 启动事件循环
    sys.exit(app.exec())
